package cn.kimoon.dau_android;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.kaopiz.kprogresshud.KProgressHUD;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import cn.kimoon.dau_android.API.ApiDAU;
import cn.kimoon.dau_android.API.AppClient;
import cn.kimoon.dau_android.Dialog.DialogManager;
import cn.kimoon.dau_android.Dialog.LoadingDialog;
import cn.kimoon.dau_android.Model.ModelLogin;
import cn.kimoon.dau_android.Utility.SPUtils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    public static final String DAU_SP_SERVER_DOMAIN = "DAU_SP_SERVER_DOMAIN";
    public static final String DAU_SP_USER_NAME     = "DAU_SP_USER_NAME";
    public static final String DAU_SP_PASSWORD      = "DAU_SP_PASSWORD";
    public static final String DAU_SP_AUTO_LOGIN    = "DAU_SP_AUTO_LOGIN";

    private EditText serverEditText;
    private EditText nameEditText;
    private EditText pwdEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 这里一定要先设置一下域名，以免第一次登录，出现了推送
        AppClient.mServerDomain = (String)SPUtils.get(this, DAU_SP_SERVER_DOMAIN, "dau.kimoon.cn");
        if ((boolean) SPUtils.get(this, DAU_SP_AUTO_LOGIN, false)) {
            jumpToHomePage();
            return;
        }

        setContentView(R.layout.activity_main);
        initActionBar();
        initSubViews();
    }

    private void initActionBar() {
//        ActionBar actionBar = getSupportActionBar();
//        actionBar.hide();
    }

    private void initSubViews() {
        serverEditText = (EditText) findViewById(R.id.login_server_edit_text);
        nameEditText = (EditText) findViewById(R.id.login_name_edit_text);
        pwdEditText = (EditText) findViewById(R.id.login_pwd_edit_text);

        Button loginBtn = (Button) findViewById(R.id.login_button);
        loginBtn.setOnClickListener(this);

        serverEditText.setText((String)SPUtils.get(this, DAU_SP_SERVER_DOMAIN, ""));
        nameEditText.setText((String)SPUtils.get(this, DAU_SP_USER_NAME, ""));
        pwdEditText.setText((String)SPUtils.get(this, DAU_SP_PASSWORD, ""));
    }

    // 按键处理
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_button:
                loginBtnTapped();
                break;
        }
    }

    // 登录按钮按下
    private void loginBtnTapped() {
        if (TextUtils.isEmpty(serverEditText.getText())) {
            Toast.makeText(this, R.string.main_server_address, Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(nameEditText.getText())) {
            Toast.makeText(this, R.string.main_input_user_name, Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(pwdEditText.getText())) {
            Toast.makeText(this, R.string.main_input_password, Toast.LENGTH_SHORT).show();
            return;
        }

        // 设置AppClient的域名(域名有空格的话，会直接崩溃)
        AppClient.mServerDomain = serverEditText.getText().toString().replaceAll(" ", "");

        requestLogin();
    }

    // 跳转到主页
    private void jumpToHomePage() {
        startActivity(new Intent(MainActivity.this, TabRootActivity.class));
        finish();
    }

    private void saveLoginDataToDisk() {
        // 极光推送alias
        String alias = nameEditText.getText().toString().trim();
        JPushInterface.setAlias(this, alias, new TagAliasCallback() {
            @Override
            public void gotResult(int i, String s, Set<String> set) {
                Log.d("MainActivity", "注册极光推送alias成功："+ i + "之前的别名：" + set);
            }
        });

        // 保存数据到本地
        SPUtils.put(this, DAU_SP_SERVER_DOMAIN, serverEditText.getText().toString().replaceAll(" ", ""));
        SPUtils.put(this, DAU_SP_USER_NAME, nameEditText.getText().toString());
        SPUtils.put(this, DAU_SP_PASSWORD, pwdEditText.getText().toString());
        SPUtils.put(this, DAU_SP_AUTO_LOGIN, true);
    }

    // 网络请求
    private void requestLogin() {
//        DialogManager.getInstance().showLoadingDialog(this, "");
        final KProgressHUD hud = KProgressHUD.create(this, KProgressHUD.Style.SPIN_INDETERMINATE).show();

        Map<String, String> parameters = new HashMap<>();
        parameters.put("account", nameEditText.getText().toString());
        parameters.put("password", pwdEditText.getText().toString());
        parameters.put("blueteeth_uuid", "1234");

        // 因为这里是单例，所以当域名输入错误的时候，就不能更改了，所以这里不能用单例
        // 可以用单例，这里我会先清空单例，强制重新生成
        AppClient.clearRetrofit();
        ApiDAU apiDAU = AppClient.retrofit().create(ApiDAU.class);
        Call<ModelLogin> call = apiDAU.apiLogin(parameters);
        call.enqueue(new Callback<ModelLogin>() {
            @Override
            public void onResponse(Call<ModelLogin> call, Response<ModelLogin> response) {
                hud.dismiss();
//                if (response.code() == 200) {
//                    if (response.body().errCode == 200) {
////                    DialogManager.getInstance().dismissLoadingDialog();
//                        saveLoginDataToDisk();
//                        jumpToHomePage();
//                    } else {
////                    DialogManager.getInstance().showToastDialog(MainActivity.this, LoadingDialog.LoadingState.STATE_FAIL, model.msg);
//                        Toast.makeText(MainActivity.this, response.body().msg, Toast.LENGTH_SHORT).show();
//                    }
//                } else {
//                    Toast.makeText(MainActivity.this, response.message(), Toast.LENGTH_SHORT).show();
//                }

                if (response.body() != null && response.body().errCode == 200) {
                    saveLoginDataToDisk();
                    jumpToHomePage();
                } else {
                    String msg = (response.body() == null ? response.message() : response.body().msg);
                    Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ModelLogin> call, Throwable t) {
//                DialogManager.getInstance().showToastDialog(MainActivity.this, LoadingDialog.LoadingState.STATE_FAIL, "网络请求失败");
                hud.dismiss();
                Toast.makeText(MainActivity.this, R.string.internet_request_failed, Toast.LENGTH_SHORT).show();
            }
        });
    }
}
